#include "historymessagewidget.h"
#include "debug.h"


/*********************************
 *  表示一个历史消息元素
 ********************************/

Historyitem *Historyitem::makeHistoryMsgItem(const Message &msg)
{
    // 1. 创建出对象
    Historyitem* item = new Historyitem();
    item->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);

    // 2. 创建布局
    QGridLayout* glayout = new QGridLayout();
    glayout->setSpacing(0);
    glayout->setContentsMargins(0,0,0,0);
    item->setLayout(glayout);

    // 3. 创建头像
    QPushButton* avatar = new QPushButton();
    avatar->setFixedSize(40,40);
    avatar->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    avatar->setIconSize(QSize(40,40));
    avatar->setIcon(QIcon(msg.sender.avatar));
    avatar->setStyleSheet("QPushButton { border: none; }");

    // 4. 创建昵称和时间
    QLabel* nameLabel = new QLabel();
    nameLabel->setText(msg.sender.nickname + "|" + msg.time);
    nameLabel->setFixedHeight(20);
    nameLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    // 5. 消息内容部分
    QWidget* contentWidget = nullptr;
    if(msg.messageType == model::TEXT_TYPE)
    {
        // 文本消息
        QLabel* label = new QLabel();
        label->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
        label->setWordWrap(true);
        label->setText(QString(msg.content));
        label->adjustSize();        // 设置让 label 能够自动调整大小
        contentWidget = label;
    }
    else if(msg.messageType == model::IMAGE_TYPE)
    {
        //TODO
    }
    else if(msg.messageType == model::FILE_TYPE)
    {
        //TODO
    }
    else if(msg.messageType == model::SPEECH_TYPE)
    {
        //TODO
    }
    else
    {
        LOG_DEBUG << "消息类型错误！messageType=" << msg.messageType << "\n";
    }

    // 6. 把上述控件添加到布局中
    glayout->addWidget(avatar,0,0,2,1);
    glayout->addWidget(nameLabel,0,1);
    glayout->addWidget(contentWidget,1,1,5,1);

    return item;
}

/*********************************
 *  展示消息窗口
 ********************************/

HistoryMessageWidget::HistoryMessageWidget(QWidget *parent)
    :QDialog(parent)
{
    // 1. 设置基本属性
    this->setFixedSize(400,500);
    this->setWindowFlag(Qt::WindowType::FramelessWindowHint);
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setAttribute(Qt::WA_TranslucentBackground);
    this->setObjectName("history");
    this->setStyleSheet("#history { background-color: rgb(243,243,243);border-radius: 15px;}");

    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0,0,0,0);
    vlayout->setAlignment(Qt::AlignTop);
    this->setLayout(vlayout);

    // 自定义标题栏
    QWidget *titleBar = new QWidget(this);
    titleBar->setObjectName("titleBar");
    titleBar->setStyleSheet("#titleBar { background-color: rgb(243,243,243);border-radius: 15px;}");
    titleBar->setFixedSize(400,30);

    QHBoxLayout* hlayout = new QHBoxLayout();
    hlayout->setSpacing(0);
    hlayout->setContentsMargins(0,0,0,0);
    hlayout->setAlignment(Qt::AlignRight);
    titleBar->setLayout(hlayout);

    QLabel *titleLabel = new QLabel();
    // titleLabel->setFixedSize(340,30);
    titleLabel->setFixedHeight(30);
    titleLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    titleLabel->setText("聊天记录");
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("color: black; font-weight: bold;");

    // 添加关闭按钮
    QPushButton *closeButton = new QPushButton();
    closeButton->setFixedSize(30,30);
    closeButton->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    closeButton->setText("X");
    closeButton->setStyleSheet("QPushButton { color: balck; border: none;border-radius: 15px} QPushButton:pressed { background-color: rgb(255, 0, 0); } QPushButton:hover { background-color: rgb(255, 0, 0); }");
    connect(closeButton, &QPushButton::clicked, this, &QDialog::close);

    // 布局
    hlayout->addWidget(titleLabel);
    hlayout->addWidget(closeButton);
    vlayout->addWidget(titleBar);

    // 2. 创建布局管理器.
    glayout = new QGridLayout();
    glayout->setSpacing(0);
    glayout->setVerticalSpacing(5);
    glayout->setContentsMargins(10,5,10,0);
    glayout->setAlignment(Qt::AlignTop);
    vlayout->addLayout(glayout);

    // 3. 创建单选按钮
    keyRadioBtn = new QRadioButton();
    timeRadioBtn = new QRadioButton();
    keyRadioBtn->setText("按关键词查询");
    timeRadioBtn->setText("按时间查询");
    // 默认按照关键词查询
    keyRadioBtn->setChecked(true);
    glayout->addWidget(keyRadioBtn,0,0,1,4);
    glayout->addWidget(timeRadioBtn,0,5,1,4);

    // 4. 创建搜索框
    searchEdit = new QLineEdit();
    searchEdit->setFixedSize(330,40);
    searchEdit->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    searchEdit->setPlaceholderText("要搜索的关键词");
    searchEdit->setStyleSheet("QLineEdit { border: none; border-radius: 10px; font-size: 16px; background-color: rgb(235, 235, 235); padding-left: 5px;}");
    glayout->addWidget(searchEdit,1,0,1,8);

    // 5. 创建搜索按钮
    searchBtn = new QPushButton();
    searchBtn->setFixedSize(40,40);
    searchBtn->setIconSize(QSize(30,30));
    searchBtn->setIcon(QIcon(":/resource/image/search.png"));
    QString BtnStyle = "QPushButton { border: none; background-color: rgb(240, 240, 240); border-radius: 10px; }";
    BtnStyle += "QPushButton:hover { background-color: rgb(220, 220, 220); } QPushButton:pressed { background-color: rgb(200, 200, 200); } ";
    searchBtn->setStyleSheet(BtnStyle);
    glayout->addWidget(searchBtn,1,8,1,1);

    // 6. 创建时间相关的部分控件, 初始情况下要隐藏
    QLabel* begTag = new QLabel();
    begTag->setText("开始时间");
    QLabel* endTag = new QLabel();
    endTag->setText("结束时间");
    begTimeEdit = new QDateTimeEdit();
    endTimeEdit = new QDateTimeEdit();
    // [联调新增]
    begTimeEdit->setDisplayFormat("yyyy-MM-dd");
    endTimeEdit->setDisplayFormat("yyyy-MM-dd");
    begTag->hide();
    endTag->hide();
    begTimeEdit->hide();
    endTimeEdit->hide();

    // 7. 创建滚动区域
    initScrollArea();

    // 8. 设置槽函数
    connect(keyRadioBtn,&QRadioButton::clicked,this,[=](){
        // 把时间相关的控件, 隐藏起来
        glayout->removeWidget(begTag);
        glayout->removeWidget(begTimeEdit);
        glayout->removeWidget(endTag);
        glayout->removeWidget(endTimeEdit);
        begTag->hide();
        begTimeEdit->hide();
        endTag->hide();
        endTimeEdit->hide();

        // 把关键词搜索框显示加入布局
        glayout->addWidget(searchEdit,1,0,1,8);
        searchEdit->show();
    });

    connect(timeRadioBtn,&QRadioButton::clicked,this,[=](){
        // 关键词搜索框隐藏并从布局中删除掉.
        glayout->removeWidget(searchEdit);
        searchEdit->hide();

        // 把时间相关的控件, 添加到布局中, 并且进行显示.
        glayout->addWidget(begTag,1,0,1,1);
        glayout->addWidget(begTimeEdit,1,1,1,3);
        glayout->addWidget(endTag,1,4,1,1);
        glayout->addWidget(endTimeEdit,1,5,1,3);
        begTag->show();
        begTimeEdit->show();
        endTag->show();
        endTimeEdit->show();
    });

    // 构造测试数据
#if TEST_UI
    for(int i = 0;i < 30;++i)
    {
        // 注意此处代码和前面的差别.
        // 前面有个代码, UserInfo 必须要 new 出来才能构造. 当时 Item 对象里, 持有了 const UserInfo& , 不是 new 的话
        // 就可能使引用指向的对象失效的.
        // 此处后续的代码, 都是按照传值的方式来使用 message 的内容, 不 new 也行.
        UserInfo sender;
        sender.userId = "1";
        sender.nickname = "小短腿" + QString::number(i);
        sender.avatar = QIcon(":/resource/image/defaultAvatar.png");
        sender.description = "";
        sender.phone = "18612345678";
        Message msg = Message::createMeaasge(model::TEXT_TYPE,"1",sender,QString("消息内容" + QString::number(i)).toUtf8());
        this->addHistoryMessage(msg);
}
#endif
}

void HistoryMessageWidget::mousePressEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::LeftButton)
    {
        m_dragPosition = event->globalPosition().toPoint() - frameGeometry().topLeft();
        event->accept();
    }
}

void HistoryMessageWidget::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton)
    {
        this->move(event->globalPosition().toPoint() - m_dragPosition);
        event->accept();
    }
}

void HistoryMessageWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);  // 抗锯齿

    // 3. 绘制圆角矩形背景
    QPainterPath path;
    path.addRoundedRect(rect(), 15, 15);  // 圆角半径
    painter.fillPath(path, QColor("#F3F3F3"));
}

void HistoryMessageWidget::initScrollArea()
{
    // 1. 创建滚动区域对象
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setFixedSize(380,400);
    scrollArea->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    // 设置滚动条相关的样式
    QString style = "QScrollBar:vertical {border: none;background: rgb(243,243,243);width: 10px;margin: 0px 0px 0px 0px;}\
        QScrollBar::handle:vertical {background: #c1c1c1;min-height: 20px;border-radius: 5px;}\
        QScrollBar::handle:vertical:hover {background: #a8a8a8;}\
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {height: 0px;}\
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {background: none;}";
    scrollArea->verticalScrollBar()->setStyleSheet(style);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0; }");
    scrollArea->setStyleSheet("QScrollArea { border: none; }");

    // 2. 创建 QWidget, 持有要加入的新的内容
    container = new QWidget();
    scrollArea->setWidget(container);

    // 3. 创建 container 中的布局管理器.
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(10);
    vlayout->setContentsMargins(10,0,0,0);
    container->setLayout(vlayout);

    glayout->addWidget(scrollArea,2,0,1,9);
}

void HistoryMessageWidget::addHistoryMessage(const Message &msg)
{
    Historyitem* item = Historyitem::makeHistoryMsgItem(msg);
    QVBoxLayout* vlayout = dynamic_cast<QVBoxLayout*>(container->layout());
    vlayout->addWidget(item);
}

void HistoryMessageWidget::clear()
{
    QVBoxLayout* vlayout = dynamic_cast<QVBoxLayout*>(container->layout());
    for(int i = vlayout->count() - 1;i >= 0;--i)
    {
        auto* item = vlayout->takeAt(i);
        if(item == nullptr || item->widget() == nullptr)
        {
            continue;
        }
        item->widget()->deleteLater();
    }
}

